class User < ApplicationRecord
  # # 存在性验证：要求 name、email 存在
  # validates :name, presence: true
  # validates :email, presence: true
  #
  # # 长度验证：name最大设置6个字符长度；password_digest最少6个字符长度
  # validates :name, length: { maximum: 6 }
  # validates :password_digest, length: { minimum: 6 }
  #
  # # 格式验证：要求email字段符合正则规则
  # VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  # validates :email, format: { with: VALID_EMAIL_REGEX }
  #
  # # 唯一性验证：要求email字段唯一
  # validates :email, uniqueness: { case_sensitive: false }

  # 使用 has_secure_password 要求 bcrypt gem 支持
  has_secure_password
  # 用户删除时删除所有微博
  has_many :microposts, dependent: :destroy

  # 配置验证规则
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :name, presence: true, length: { maximum: 6 }
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
  validates :password_digest, length: { minimum: 6 }

  # 回调函数：在保存前将邮箱转换为小写
  before_save :downcase_email

  private

  # 私有方法：将邮箱转换为小写
  def downcase_email
    self.email = email.downcase
  end
end
